<%@ tag language="java" pageEncoding="UTF-8" %>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<%@ attribute name="recordId" required="true" rtexprvalue="true"%>
<%@ attribute name="moduleCode" required="true" rtexprvalue="true"%>

<div id="userCommentPanel"  ng-controller="UserCommentCtrl">    
  <p><button type="button" class="btn" ng-click="reloadComments();"><i class="icon-refresh"></i> <s:message code="btn.refresh"/></button></p>                            
  <div>
    <p><textarea rows="3" cols="" id="userCommentContent" name="userCommentContent" placeholder="<s:message code="userComment.content.help" />" class="input-block-level" ng-keyup="publishComment($event)"></textarea></p>
    <p class="text-right"><button type="button" class="btn btn-info" ng-click="saveComment();"><s:message code="userComment.func.save" /></button></p>
  </div>
  
  <div class="media" style="border-bottom: 1px dashed #EAEAEA;" ng-repeat="row in userComments" id="userCommentRow{{$index}}">
    <a class="pull-left" href="#">
      <img class="user-photo" src="${contextPath }/upload/avatar/avatar.gif"  ng-if="!row.createUserAvatar">
      <img class="user-photo" src="${contextPath }/upload/avatar/{{row.createUserAvatar}}_2.jpg"  ng-if="row.createUserAvatar">
    </a>
    <div class="media-body">
      <p class="media-heading">{{row.createUsername}}:{{row.content}}</p>
      <p>{{row.createDatetime | date:"yyyy-MM-dd HH:mm:ss"}}&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" ng-click="deleteComment($index);"><s:message code="btn.delete"></s:message></a></p>
    </div>
  </div>  
    
</div>

<script type="text/javascript">
$(document).ready(function(){ 
  
  angular.element(document).ready(function() {  
    angular.bootstrap(document, [
            function ($httpProvider) {
              
              // Use x-www-form-urlencoded Content-Type
                $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
               
                /**
                 * The workhorse; converts an object to x-www-form-urlencoded serialization.
                 * @param {Object} obj
                 * @return {String}
                 */ 
                var param = function(obj) {
                  var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
                    
                  for(name in obj) {
                    value = obj[name];
                      
                    if(value instanceof Array) {
                      for(i=0; i<value.length; ++i) {
                        subValue = value[i];
                        fullSubName = name + '[' + i + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                      }
                    }
                    else if(value instanceof Object) {
                      for(subName in value) {
                        subValue = value[subName];
                        fullSubName = name + '[' + subName + ']';
                        innerObj = {};
                        innerObj[fullSubName] = subValue;
                        query += param(innerObj) + '&';
                      }
                    }
                    else if(value !== undefined && value !== null)
                      query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
                  }
                    
                  return query.length ? query.substr(0, query.length - 1) : query;
                };
               
                // Override $http service's default transformRequest
                $httpProvider.defaults.transformRequest = [function(data) {
                  return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
                }];
              } 
        ]);  
      });
}); 

function UserCommentCtrl($scope, $http) {
  $scope.userComments = [];
  $scope.formData = {};
  //init
  $http.get('${contextPath}/assistant/userComment/getComments.json?moduleCode=${moduleCode}&recordId=${recordId}', {
  }).success(function(data) {
      $scope.userComments = data.userComments;      
  }); 
  
  $scope.reloadComments = function(){
    $http.get('${contextPath}/assistant/userComment/getComments.json?moduleCode=${moduleCode}&recordId=${recordId}', {
    }).success(function(data) {
        $scope.userComments = data.userComments;      
    }); 
  }
  
  $scope.publishComment = function(e){
    var keycode = window.event?e.keyCode:e.which;
    if(e.ctrlKey && keycode == 13 || keycode == 10) { 
      var content = $("#userCommentContent").val();
      var p = $http.post("${contextPath}/assistant/userComment/save.json", {
        "moduleCode" : "${moduleCode}",
        "recordId" : "${recordId}",
        "content" : content
      });
      p.success(function(data){
        var userComment = data.userComment;
        $scope.userComments.unshift(userComment);
        $("#userCommentContent").val("");
      });
      p.error(function(response, status, headers, config){
          $.pnotify({       
              title: response.exception,
              type: 'error',
              hide: true,
              history: false,           
              sticker: false
          });     
      }); 
    }
  }
  
  $scope.saveComment = function() {
    var content = $("#userCommentContent").val();
    var p = $http.post("${contextPath}/assistant/userComment/save.json", {
      "moduleCode" : "${moduleCode}",
      "recordId" : "${recordId}",
      "content" : content
    });
    p.success(function(data){
      var userComment = data.userComment;
      $scope.userComments.unshift(userComment);
      $("#userCommentContent").val("");
    });
    p.error(function(response, status, headers, config){
        $.pnotify({       
            title: response.exception,
            type: 'error',
            hide: true,
            history: false,           
            sticker: false
        });     
    }); 
  };
  
  $scope.deleteComment = function(index) {  
    var row = $scope.userComments[index];
    bootbox.confirm("<s:message code='common.delete.confirm' />", function(result){
    if(result)
    {
          var p = $http.post("${contextPath}/assistant/userComment/delete.json", {
            "id": row.id
          });
          p.success(function(response, status, headers, config){
            $scope.userComments.splice(index, 1);         
          });
    }
    }); 
  };
  
}
</script> 